package com.zhan.ielts.web.controller;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import com.zhan.ielts.enums.OperationSysEnum;
import com.zhan.ielts.enums.ProductEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zhan.frame.core.dao.BaseService;
import com.zhan.frame.core.web.controller.BaseControllerImpl;
import com.zhan.frame.core.web.domain.CustomResult;
import com.zhan.ielts.domain.PushMessage;
import com.zhan.ielts.domain.QueOppCla;
import com.zhan.ielts.domain.query.PushMessageQuery;
import com.zhan.ielts.domain.vo.PushMessageVo;
import com.zhan.ielts.service.PushMessageService;

@Controller
@RequestMapping("/push/message")
public class PushMessageController extends BaseControllerImpl<PushMessage, PushMessageQuery> {

	private Logger log = LoggerFactory.getLogger(PushMessageController.class);

	@Autowired
	private PushMessageService pushMessageService;

	// @Autowired
	// private PushStatisticsService pushStatisticsService;
	//
	// @Autowired
	// private QueOppClaService queOppClaService;

	@Override
	protected BaseService<PushMessage> getBaseService() {
		return pushMessageService;
	}

	@ResponseBody
	@RequestMapping(value = "/addToken", method = RequestMethod.POST)
	public CustomResult addOneToken(PushMessage entity) {
		log.debug("添加token开始");

		try {
			PushMessage query = new PushMessage();
			query.setTokenNum(entity.getTokenNum());
            query.setMode(entity.getMode());
			query.setAppName(entity.getAppName());
			Long count = pushMessageService.queryCount(query);
			log.debug("count=" + count);
			if (count < 1) {
				pushMessageService.insert(entity);
			} else {
				log.debug("token已存在！");
				return new CustomResult(1, "此appName,mode模式下的token已存在！", null);
			}
		} catch (Exception e) {
			log.debug("网络或系统错误！");
			return new CustomResult(0, "网络或系统错误！", null);
		}

		log.debug("添加token结束");
		return new CustomResult(1, "", entity);
	}

	/**
	 * @function 修改token，供其它服务调用
	 * @param entity
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/editToken", method = RequestMethod.POST)
	public CustomResult editOneToken(PushMessage entity) {
		log.debug("修改token开始");
		try {
			PushMessage query = new PushMessage();
			query.setTokenNum(entity.getTokenNum());
			Long count = pushMessageService.queryCount(query);
			log.debug("count=" + count);
			if (count > 0) {
				pushMessageService.updateByFields(entity);
			} else {
				pushMessageService.insert(entity);
			}
		} catch (Exception e) {
			log.debug("网络或系统错误！");
			return new CustomResult(0, "网络或系统错误！", null);
		}

		log.debug("修改token结束");
		return new CustomResult(1, "", entity);
	}

	@ResponseBody
	@RequestMapping(value = "/send", method = RequestMethod.POST)
	public CustomResult send(PushMessageVo entity) {
		log.debug("消息推送开始");
		log.debug("entity.getMode = " + entity.getMode());

		try {
			QueOppCla queOppCla = new QueOppCla();

			// 只对真题做处理
			queOppCla.setQueType(entity.getQueType());
			// if (entity.getQueType() == 2) {
			// queOppCla = queOppClaService.queryOne(queOppCla);
			// }

			PushMessageQuery pushMessageQuery = new PushMessageQuery();
			pushMessageQuery.setContent(entity.getContent());
			pushMessageQuery.setMode(entity.getMode());
			pushMessageQuery.setTokenNumLike(entity.getTokenNum());
			pushMessageQuery.setAppName(entity.getAppName());
			pushMessageQuery.setWantReceive("YES");

			// List<PushMessage> pushMessageList =
			// pushMessageService.queryList(pushMessageQuery);

			List<PushMessage> pushMessageList = new ArrayList<PushMessage>();

			String[] appNames = entity.getAppName().split(",");
			for (String appName : appNames) {
				pushMessageQuery.setAppName(appName.trim());
				pushMessageList.addAll(pushMessageService.queryList(pushMessageQuery));
				log.info("pushMessageList.size()---" + pushMessageList.size());
			}

			// 推送消息
			if (pushMessageList != null && pushMessageList.size() > 0) {

				Integer count = pushMessageList.size();
				Integer maxSize = 1000;
				DecimalFormat df = new DecimalFormat("0.000");// 格式化小数，不足的补0
				String num = df.format((float) count / maxSize);// 返回的是String类型的
				Integer circle = (int) Math.ceil(new Double(num));

				List<PushMessage> subPushMessageList = null;

				for (int i = 0; i < circle; i++) {
					Integer toIndex = (i + 1) * maxSize < count ? ((i + 1) * maxSize) : count;
					subPushMessageList = pushMessageList.subList(i * maxSize, toIndex);
					pushMessageService.pushMessage(subPushMessageList, entity, queOppCla);
					log.info("pushMessageList.size()---subPushMessageList.size()" + pushMessageList.size() + "---"
							+ subPushMessageList.size());
					Thread.sleep(10*1000);

				}

				// pushMessageService.pushMessage(pushMessageList,
				// pushMessageQuery, queOppCla);
			}

			// 保存推送统计信息
			if (pushMessageList != null && pushMessageList.size() > 0) {
				entity.setCount((long) pushMessageList.size());
				// pushStatisticsService.savePushStatistics(entity);
			}
		} catch (Exception e) {
			log.debug("消息推送失败！");
			return new CustomResult(0, "消息推送失败！", entity);
		}
		log.debug("消息推送结束！");

		log.debug("消息推送结束");
		return new CustomResult(1, "推送完成", entity);
	}
	private String wrapAppName(PushMessageVo entity) {
		String appName = entity.getApplication();
		String platForm = OperationSysEnum.getNameByIndex(entity.getPlatform());
		if (platForm == null) {
			platForm = "all";
		}
		if (ProductEnum.tpo_iPad.getName().equals(appName) && entity.getPlatform() != 2) {

		} else {
			appName = appName + "_" + platForm;
		}
		if ("all_all".equals(appName)) {
			appName = null;
		}
		return appName;
	}
	@ResponseBody
	@RequestMapping(value = "/mode", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public ModelAndView pushMessage(PushMessageVo entity) {
		log.debug("消息推送开始！");
		log.debug("entity.getMode = " + entity.getMode());

		try {
			QueOppCla queOppCla = new QueOppCla();

			queOppCla.setQueType(entity.getPoint());
			/*if (entity.getPoint() == 2) {
				queOppCla = queOppClaService.queryOne(queOppCla);
			}*/
			PushMessageQuery pushMessageQuery = new PushMessageQuery();
			pushMessageQuery.setContent(entity.getContent());
			pushMessageQuery.setMode(entity.getMode());
			pushMessageQuery.setTokenNumLike(entity.getTokenNum());
			pushMessageQuery.setAppName(wrapAppName(entity));
			pushMessageQuery.setWantReceive("YES");
			if (pushMessageQuery.getAppName() != null && pushMessageQuery.getAppName().startsWith("all")) {
				String appName = pushMessageQuery.getAppName().split("_")[1];
				if(appName.equals(ProductEnum.tpo.getName())){
					appName=appName+"_";
				}
				pushMessageQuery.setAppNameLike(pushMessageQuery.getAppName().split("_")[1]);
			}
			if (pushMessageQuery.getAppName() != null && pushMessageQuery.getAppName().endsWith("all")) {
				pushMessageQuery.setAppNameLike(pushMessageQuery.getAppName().split("_")[0]);
			}
			if (pushMessageQuery.getAppName() != null && pushMessageQuery.getAppName().contains("all")) {
				pushMessageQuery.setAppName(null);
			}
			// List<PushMessage> pushMessageList =
			// pushMessageService.queryList(pushMessageQuery);

			List<PushMessage> pushMessageList = new ArrayList<PushMessage>();
			pushMessageList.addAll(pushMessageService.queryList(pushMessageQuery));
			/*
			 * String[] appNames = entity.getAppName().split(","); for (String
			 * appName : appNames) {
			 * pushMessageQuery.setAppName(appName.trim());
			 *
			 * log.info("pushMessageList.size()---" + pushMessageList.size()); }
			 */

			// 推送消息
			if (pushMessageList != null && pushMessageList.size() > 0) {

				Integer count = pushMessageList.size();
				Integer maxSize = 1000;
				DecimalFormat df = new DecimalFormat("0.000");// 格式化小数，不足的补0
				String num = df.format((float) count / maxSize);// 返回的是String类型的
				Integer circle = (int) Math.ceil(new Double(num));

				List<PushMessage> subPushMessageList = null;

				for (int i = 0; i < circle; i++) {
					Integer toIndex = (i + 1) * maxSize < count ? ((i + 1) * maxSize) : count;
					subPushMessageList = pushMessageList.subList(i * maxSize, toIndex);
					pushMessageService.pushMessage(subPushMessageList, entity, queOppCla);
					log.info("pushMessageList.size()---subPushMessageList.size()" + pushMessageList.size() + "---"
							+ subPushMessageList.size());
					Thread.sleep(5000);
					if (i % 10 == 0) {
						Thread.sleep(2 * 60 * 1000);
					}
				}

				// pushMessageService.pushMessage(pushMessageList,
				// pushMessageQuery, queOppCla);
			}

			// 保存推送统计信息
			//这个看之前的代码没有，所以先注掉
			/*if (pushMessageList != null && pushMessageList.size() > 0) {
				entity.setCount((long) pushMessageList.size());
				String appName = wrapAppName(entity);
				if (appName == null) {
					appName = "all_all";
				}
				entity.setAppName(appName);
				pushStatisticsService.savePushStatistics(entity);
			}*/
		} catch (Exception e) {
			log.debug("消息推送失败！");
			return new ModelAndView(path.getListViewPath());
		}
		log.debug("消息推送结束！");

		return new ModelAndView(path.getListViewPath());
	}

	/**
	 * @function 修改token，供其它服务调用
	 * @param entity
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/opp", method = RequestMethod.POST)
	public ModelAndView pushMessageOpp(PushMessageVo entity) {
		log.debug("消息推送开始！");
		log.debug("entity.getOppId, getQueType = " + entity.getOppId() + "--" + entity.getQueType());

		try {
			QueOppCla queOppCla = new QueOppCla();
			queOppCla.setId(entity.getOppId());
			queOppCla.setQueType(entity.getQueType());
			queOppCla.setOppName(entity.getOppName());
			queOppCla.setType(entity.getType());

			PushMessageQuery pushMessageQuery = new PushMessageQuery();
			pushMessageQuery.setContent(entity.getContent());
			pushMessageQuery.setMode(entity.getMode());
			pushMessageQuery.setTokenNumLike(entity.getTokenNum());
			pushMessageQuery.setAppName(entity.getAppName());
			pushMessageQuery.setWantReceive("YES");

			List<PushMessage> pushMessageList = pushMessageService.queryList(pushMessageQuery);

			// 推送消息
			if (pushMessageList != null && pushMessageList.size() > 0) {
				pushMessageService.pushMessage(pushMessageList, entity, queOppCla);
			}

			// 保存推送统计信息
			if (pushMessageList != null && pushMessageList.size() > 0) {
				// pushStatisticsService.savePushStatistics(entity);
			}

		} catch (Exception e) {
			log.debug("消息推送失败！");
			return new ModelAndView("redirect:/que/opp/cla/");
		}

		log.debug("消息推送结束！");

		log.debug("path.getRedirectListPath()==" + path.getRedirectListPath());
		return new ModelAndView("redirect:/que/opp/cla/");

	}

}
